package mytest.stallings;

import sde.semaforo.Semaforo;
import sde.semaforo.SemaforoBinario;
import sde.semaforo.SemaforoContatore;

public class StallingsABAAB {

	private static class A implements Runnable{

		private Semaforo mutex;
		private Semaforo mutexAB;
		private Semaforo a;
		private Semaforo b;
		
		public A(Semaforo mutex, Semaforo mutexAB, Semaforo a, Semaforo b){
			this.a=a;
			this.mutexAB=mutexAB;
			this.b=b;
			this.mutex=mutex;
		}
		
		@Override
		public void run() {
//			while(true){
				a.P();
				mutexAB.P();
				System.out.println("A");
				b.V();
				mutexAB.V();
//			}
		}
	}
	
	private static class B implements Runnable{

		private Semaforo mutex;
		private Semaforo mutexAB;
		private Semaforo a;
		private Semaforo b;
		
		public B(Semaforo mutex, Semaforo mutexAB, Semaforo a, Semaforo b){
			this.a=a;
			this.mutexAB=mutexAB;
			this.b=b;
			this.mutex=mutex;
		}
		
		@Override
		public void run() {
//			while(true){
				mutex.P();
				b.P();
				b.P();
				mutexAB.P();
				System.out.println("B");
				a.V();
				a.V();
				mutex.V();
				mutexAB.V();
			}
//		}
	}
	
	public static void main(String[] args) {
		
		Semaforo mutex=new SemaforoBinario(1);
		Semaforo mutexAB = new SemaforoBinario(1);
		Semaforo a = new SemaforoContatore(1);
		Semaforo b = new SemaforoContatore(1);
		
		for(int i=0;i<3;i++){
			new Thread(new A(mutex, mutexAB, a, b)).start();
		}
		for(int i=0; i<2;i++){
			new Thread(new B(mutex, mutexAB, a, b)).start(); 
		}
	}
}
